<?php
function validateUsername($name){
	//NO cumple longitud minima
	if(strlen($name) < 1)
		return false;
	//SI longitud pero NO solo caracteres A-z
	else if(!preg_match("/^[a-zA-Z]+$/", $name))
		return false;
	// SI longitud, SI caracteres A-z
	else
		return true;
}

function validateEmail($email){
	//NO hay nada escrito
	if(strlen($email) == 0)
		return false;
	// SI escrito, NO VALIDO email
	else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
		return false;
	// SI rellenado, SI email valido
	else
		return true;
}


//guardamos las variables del formulario
$name          = $_POST['nombre'];
$firstSurname  = $_POST['apellido1'];
$secondSurname = $_POST['apellido2'];
$email         = $_POST['email'];
include "conexion.php";
$query1="select * from member where member_email='$email'";
$result1=mysql_query($query1);
include "cerrar_conexion.php";
if(mysql_num_rows($result1)>=1)
{
	?> 
	   	 <head> 
	    	<script>
            	window.alert("This email already exist");
                history.back();
            </script>
	    </head> 
    	<?php
}

	if(!validateUsername($name))
		$name = "error";
	if(!validateUsername($firstSurname))
		$firstSurname = "error";
	if(!validateUsername($secondSurname))
		$secondSurname = "error";
	if(!validateEmail($_POST['email']))
		$email = "error";


	//Comprobamos si todo ha ido bien
	if($name != "error" && $firstSurname != "error" && $secondSurname != "error" && $email != "error"){
		//conectamos a la db
		include "conexion.php";
	
		//realizamos la consulta (insert)
		$query =	"	INSERT INTO Member(member_name,member_surname1,member_surname2,member_email)";
		$query.=	"	VALUES ('$name', '$firstSurname', '$secondSurname', '$email') ";
		mysql_query($query) or die("Error en la consulta SQL");
		include "cerrar_conexion.php";
		header('Location: http://localhost/grupo5/Listofemployees.php');
	}else{
		 ?> 
	   	 <head> 
	    	<script>
            	window.alert("Complete all fields correctly");
                history.back();
            </script>
	    </head> 
    	<?php		
	}
?>